<template>
  <div class="member-management">
    <!-- 页面标题 -->
    <el-page-header @back="handleBack" content="会员管理"></el-page-header>

    <!-- 功能按钮区 -->
    <el-row :gutter="20" class="btn-group">
      <el-col :span="8">
        <el-input v-model="searchKey" placeholder="输入会员姓名/手机号搜索" clearable>
          <template #append>
            <el-button type="primary" @click="getMemberList">搜索</el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="16" class="text-right">
        <el-button type="primary" @click="openAddDialog">新增会员</el-button>
      </el-col>
    </el-row>

    <!-- 会员列表 -->
    <el-table :data="memberList" border style="width: 100%; margin-top: 20px">
      <el-table-column prop="id" label="会员ID" width="80"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
      <el-table-column prop="balance" label="余额(元)" width="120">
        <template #default="scope">{{ formatCurrency(scope.row.balance) }}</template>
      </el-table-column>
      <el-table-column prop="points" label="积分" width="100"></el-table-column>
      <el-table-column prop="createdTime" label="注册时间" width="180">
        <template #default="scope">{{ formatDate(scope.row.createdTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button size="small" @click="openRechargeDialog(scope.row)">充值</el-button>
          <el-button size="small" type="success" @click="openExchangeDialog(scope.row)">积分兑换</el-button>
          <el-button size="small" type="warning" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px"
    ></el-pagination>

    <!-- 新增/编辑会员弹窗 -->
    <el-dialog :title="dialogTitle" v-model="memberDialogVisible" width="500px">
      <el-form :model="formData" :rules="rules" ref="memberForm" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入11位手机号"></el-input>
        </el-form-item>
        <el-form-item label="初始余额" prop="balance">
          <el-input v-model="formData.balance" type="number" min="0" step="0.01"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="memberDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitMemberForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 充值弹窗 -->
    <el-dialog title="会员充值" v-model="rechargeDialogVisible" width="400px">
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeForm" label-width="100px">
        <el-form-item label="会员姓名" disabled>
          <el-input v-model="rechargeForm.name"></el-input>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="rechargeForm.amount" type="number" min="0.01" step="0.01"></el-input>
        </el-form-item>
        <el-form-item label="赠送金额" disabled>
          <el-input v-model="giftAmount" placeholder="充100赠10元"></el-input>
        </el-form-item>
        <el-form-item label="到账总额" disabled>
          <el-input v-model="totalAmount"></el-input>
        </el-form-item>
        <el-form-item label="获得积分" disabled>
          <el-input v-model="earnPoints"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rechargeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRecharge">确认充值</el-button>
      </template>
    </el-dialog>

    <!-- 积分兑换弹窗 -->
    <el-dialog title="积分兑换" v-model="exchangeDialogVisible" width="400px">
      <el-form :model="exchangeForm" :rules="exchangeRules" ref="exchangeForm" label-width="100px">
        <el-form-item label="会员姓名" disabled>
          <el-input v-model="exchangeForm.name"></el-input>
        </el-form-item>
        <el-form-item label="当前积分" disabled>
          <el-input v-model="exchangeForm.currentPoints"></el-input>
        </el-form-item>
        <el-form-item label="兑换积分" prop="points">
          <el-input v-model="exchangeForm.points" type="number" min="1"></el-input>
        </el-form-item>
        <el-form-item label="兑换金额" disabled>
          <el-input v-model="exchangeAmount"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exchangeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExchange">确认兑换</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/axios/http'

// 分页参数
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKey = ref('')

// 会员列表数据
const memberList = ref([])

// 弹窗控制
const memberDialogVisible = ref(false)
const rechargeDialogVisible = ref(false)
const exchangeDialogVisible = ref(false)
const dialogTitle = ref('新增会员')

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  phone: '',
  balance: 0
})

// 充值表单
const rechargeForm = reactive({
  id: null,
  name: '',
  amount: 0
})

// 积分兑换表单
const exchangeForm = reactive({
  id: null,
  name: '',
  currentPoints: 0,
  points: 0
})

// 计算属性 - 充值赠送相关
const giftAmount = computed(() => {
  // 充值赠送比例：10%（充100赠10）
  return (rechargeForm.amount * 0.1).toFixed(2)
})

const totalAmount = computed(() => {
  // 总到账金额 = 充值金额 + 赠送金额
  return (Number(rechargeForm.amount) + Number(giftAmount.value)).toFixed(2)
})

const earnPoints = computed(() => {
  // 1元=1积分（按到账总额计算）
  return Math.floor(Number(totalAmount.value))
})

// 计算属性 - 积分兑换相关
const exchangeAmount = computed(() => {
  // 1积分=0.1元
  return (exchangeForm.points * 0.1).toFixed(2)
})

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  balance: [{ type: 'number', min: 0, message: '余额不能为负数', trigger: 'blur' }]
})

const rechargeRules = reactive({
  amount: [{ type: 'number', min: 0.01, message: '充值金额必须大于0', trigger: 'blur' }]
})

const exchangeRules = reactive({
  points: [
    { type: 'number', min: 1, message: '兑换积分必须大于0', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > exchangeForm.currentPoints) {
          callback(new Error('兑换积分不能超过当前积分'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 获取会员列表
const getMemberList = async () => {
  try {
    // 显示加载状态
    ElMessage({
      message: '加载中...',
      type: 'info',
      duration: 0,
      showClose: true
    })

    const res = await http.post('/glsb/get_member_by', {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      name: searchKey.value,
      phone: searchKey.value
    })

    // 关闭加载状态
    ElMessage.closeAll()

    // 检查响应结构
    if (res && res.result === 'success' && res.data) {
      memberList.value = res.data.list || []
      total.value = res.data.total || 0
    } else if (res && res.data && res.data.code === 200) {
      // 兼容原来的code判断
      memberList.value = res.data.data.list || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error(res?.data?.msg || res?.message || '获取会员列表失败')
    }
  } catch (error) {
    ElMessage.closeAll()
    ElMessage.error('网络错误：' + error.message)
  }
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  getMemberList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  getMemberList()
}

// 打开新增会员弹窗
const openAddDialog = () => {
  dialogTitle.value = '新增会员'
  Object.assign(formData, { id: null, name: '', phone: '', balance: 0 })
  memberDialogVisible.value = true
}

// 打开编辑弹窗
const openEditDialog = (row) => {
  dialogTitle.value = '编辑会员'
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    phone: row.phone,
    balance: row.balance
  })
  memberDialogVisible.value = true
}

// 打开充值弹窗
const openRechargeDialog = (row) => {
  Object.assign(rechargeForm, {
    id: row.id,
    name: row.name,
    amount: 0
  })
  rechargeDialogVisible.value = true
}

// 打开积分兑换弹窗
const openExchangeDialog = (row) => {
  Object.assign(exchangeForm, {
    id: row.id,
    name: row.name,
    currentPoints: row.points,
    points: 0
  })
  exchangeDialogVisible.value = true
}

// 提交会员表单（新增/编辑）
const submitMemberForm = async () => {
  try {
    if (formData.id) {
      // 编辑会员
      const res = await http.post('/glsb/modify_memberby_id', formData)
      if (res.result === 'success' || (res.data && res.data.code === 200)) {
        ElMessage.success('编辑成功')
        memberDialogVisible.value = false
        getMemberList()
      } else {
        ElMessage.error(res?.data?.msg || res?.message || '编辑失败')
      }
    } else {
      // 新增会员
      const res = await http.post('/glsb/add_one_member', formData)
      if (res.result === 'success' || (res.data && res.data.code === 200)) {
        ElMessage.success('新增成功')
        memberDialogVisible.value = false
        getMemberList()
      } else {
        ElMessage.error(res?.data?.msg || res?.message || '新增失败')
      }
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message)
  }
}

// 提交充值
const submitRecharge = async () => {
  try {
    const res = await http.post('/glsb/member_recharge', {
      id: rechargeForm.id,
      amount: Number(rechargeForm.amount)
    })

    if (res.result === 'success' || (res.data && res.data.code === 200)) {
      ElMessage.success('充值成功')
      rechargeDialogVisible.value = false
      getMemberList()
    } else {
      ElMessage.error(res?.data?.msg || res?.message || '充值失败')
    }
  } catch (error) {
    ElMessage.error('充值失败：' + error.message)
  }
}

// 提交积分兑换
const submitExchange = async () => {
  try {
    const res = await http.post('/glsb/member_exchange', {
      id: exchangeForm.id,
      points: exchangeForm.points
    })

    if (res.result === 'success' || (res.data && res.data.code === 200)) {
      ElMessage.success('积分兑换成功')
      exchangeDialogVisible.value = false
      getMemberList()
    } else {
      ElMessage.error(res?.data?.msg || res?.message || '兑换失败')
    }
  } catch (error) {
    ElMessage.error('兑换失败：' + error.message)
  }
}

// 删除会员
const handleDelete = async (id) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
        '确定要删除该会员吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    if (confirmResult === 'confirm') {
      const res = await http.post('/glsb/remove_memberby_id', { id })
      if (res.result === 'success' || (res.data && res.data.code === 200)) {
        ElMessage.success('删除成功')
        getMemberList()
      } else {
        ElMessage.error(res?.data?.msg || res?.message || '删除失败')
      }
    }
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('删除失败：' + error.message)
  }
}

// 格式化金额
const formatCurrency = (value) => {
  if (value === null || value === undefined) return '0.00'
  return Number(value).toFixed(2)
}

// 格式化日期 - 修复时间戳处理问题
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  // 确保是数字类型的时间戳
  const ts = typeof timestamp === 'number' ? timestamp : Number(timestamp)
  // 处理毫秒级时间戳（如果是13位则直接使用，否则转换为毫秒）
  const msTimestamp = ts.toString().length === 10 ? ts * 1000 : ts
  const date = new Date(msTimestamp)

  // 检查日期是否有效
  if (isNaN(date.getTime())) return ''

  return date.toLocaleString()
}

// 返回上一页
const handleBack = () => {
  window.history.back()
}

// 页面加载时获取会员列表
onMounted(() => {
  getMemberList()
})
</script>

<style scoped>
.btn-group {
  margin-top: 20px;
  margin-bottom: 10px;
}
</style>